package com.aaron.gesturehelper;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Environment;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.widget.Toast;

public class Setting extends PreferenceActivity {
	
	private CheckBoxPreference mEnable;
	private CheckBoxPreference mVibrate;
	private CheckBoxPreference mLockGestureViewPosition;
	
	private BroadcastReceiver mReceiver;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.layout.setting);
        mEnable = (CheckBoxPreference) findPreference(MyConfiguration.ENABLE);
        mEnable.setOnPreferenceClickListener(new OnPreferenceClickListener() {
			
			@Override
			public boolean onPreferenceClick(Preference preference) {
				if(!mEnable.isChecked()) {
					mEnable.setChecked(false);
					stopService(new Intent(Setting.this, MyService.class));
				} else {
					Toast.makeText(Setting.this, R.string.waitforserver, Toast.LENGTH_SHORT).show();
					mEnable.setEnabled(false);
					startService(new Intent(Setting.this, MyService.class));
				}
				return true;
			}
		});
        
        boolean enable = MyConfiguration.getInstance(this).getBoolean(MyConfiguration.ENABLE, false);
        mEnable.setChecked(enable);
        
        mVibrate = (CheckBoxPreference) findPreference(MyConfiguration.VIBRATE);
        mVibrate.setOnPreferenceChangeListener(new OnPreferenceChangeListener(){

			@Override
			public boolean onPreferenceChange(Preference preference,
					Object newValue) {
				Intent intent = new Intent(Contants.INTENT_CONFIGURATION_CHANGED);
				intent.putExtra(MyConfiguration.VIBRATE, true);
				sendBroadcast(intent);
				return true;
			}
        });
             
        mLockGestureViewPosition = (CheckBoxPreference) findPreference(MyConfiguration.LOCKPOSITION);
        mLockGestureViewPosition.setOnPreferenceChangeListener(new OnPreferenceChangeListener(){

			@Override
			public boolean onPreferenceChange(Preference preference,
					Object newValue) {
				Intent intent = new Intent(Contants.INTENT_CONFIGURATION_CHANGED);
				intent.putExtra(MyConfiguration.LOCKPOSITION, true);
				sendBroadcast(intent);
				return true;
			}
        });
        
        if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        	Toast.makeText(this, R.string.sdnotmount, Toast.LENGTH_SHORT).show();
        } 
        
        String workpath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/GestureHelper/";
        File dir = new File(workpath);
        if(!dir.exists()) {
        	dir.mkdir();
        }
        
        String version = getVersionInfo();
        
        uploadFile("CommandHandleServer.jar", version);
        
        MyConfiguration.getInstance(this).setString(MyConfiguration.VERSIONNAME, version);
        
        findPreference(MyConfiguration.ABOUT).setOnPreferenceClickListener(new OnPreferenceClickListener() {
			
			@Override
			public boolean onPreferenceClick(Preference preference) {
				AlertDialog.Builder builder = new AlertDialog.Builder(Setting.this);
				builder.setTitle(R.string.app_name).setMessage(R.string.advice).setPositiveButton(android.R.string.ok, new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent(
								android.content.Intent.ACTION_SEND);
						intent.setType("plain/text");
						intent.putExtra(android.content.Intent.EXTRA_EMAIL,getString(R.string.myemail));
						startActivity(Intent.createChooser(intent,getString(R.string.sendemail)));
					}
				}).setNegativeButton(android.R.string.cancel, null).show();
				return true;
			}
		});
        
    	mReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				if(action.equals(Contants.INTENT_SERVER_SUCCESS)) {
					mEnable.setEnabled(true);
					mEnable.setChecked(true);
				} else {
					mEnable.setEnabled(true);
					mEnable.setChecked(false);
				}
			}
		};
		
		IntentFilter filter = new IntentFilter(Contants.INTENT_SERVER_FAIL);
		filter.addAction(Contants.INTENT_SERVER_SUCCESS);
		registerReceiver(mReceiver, filter);
    }
    
    public void onResume() {
    	super.onResume();
      
		boolean rooted = MyConfiguration.getInstance(this).getBoolean(MyConfiguration.ROOTED, false);
		if(!rooted) {
			boolean flag = getRootAhth();
			MyConfiguration.getInstance(this).setBoolean(MyConfiguration.ROOTED, flag);
			if(!flag) {
				mEnable.setEnabled(false);
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle(R.string.app_name).setMessage(R.string.noroot);
				builder.setPositiveButton(android.R.string.ok,null);
				builder.show();
			}
		}
    }
    
    public void onDestroy() {
    	super.onDestroy();
    	unregisterReceiver(mReceiver);
    	mReceiver = null;
    }
    
    public void onConfigurationChanged(Configuration config) {
    	super.onConfigurationChanged(config);
    }
    
	private boolean getRootAhth() {
		Process process = null;
		DataOutputStream os = null;
		try {
			process = Runtime.getRuntime().exec("su");
			os = new DataOutputStream(process.getOutputStream());
			os.writeBytes("exit\n");//for emulator, it throws Broken pipe exception,WHY?
			os.flush();
			int exitValue = process.waitFor();
			if (exitValue == 0) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				if (os != null) {
					os.close();
					os = null;
				}
				if(process != null) {
					process.destroy();
					process = null;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
    
	private String getVersionInfo() {
		PackageInfo pkg = null;
		try {
			pkg = getPackageManager().getPackageInfo(getPackageName(), 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return "1-1.0";
		}
		return pkg.versionCode+"-"+pkg.versionName;
	}
	
    private void uploadFile(String filename, String version) {
    	File f = new File(getFilesDir(),filename);
    	String savedversion = MyConfiguration.getInstance(this).getString(MyConfiguration.VERSIONNAME, "1-1.0");

		if(!savedversion.equals(version)) {
			if(f.exists()) {
				f.delete();
			}
		}
    	
    	FileOutputStream out = null;
    	InputStream in = null;
    	if(!f.exists()) {
    		try {
				f.createNewFile();
				out = new FileOutputStream(f);
				in = getAssets().open(filename);
				byte[] buf = new byte[1024];
				int len;
				while((len = in.read(buf))!= -1) {
					out.write(buf, 0, len);
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if(out != null) {
					try {
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					out = null;
				}
				if(in != null) {
					try {
						in.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					in = null;
				}
			}
    	}
    }
}